const User =  require('../models/System/User')
const jwt = require('jsonwebtoken')
const assert = require('http-assert')

module.exports = options => async (req,res,next)=>{
    const token = String(req.headers.authorization || '').split(' ').pop()
    assert(token, 401, '请先登录')
    const { id } = jwt.verify(token, req.app.get('secret'))
    assert(id, 401, '请先登录')
    req.user = await User.findById(id)
    assert(req.user, 401, '请先登录')
    // role 校验用户类型
    req.role = req.user.role === req.app.get('role')
    await next()
}